package com.atguigu.tingshu.order.config.sign;

import com.atguigu.tingshu.order.config.key.ConstantsProperties;
import jakarta.annotation.Resource;

import java.security.*;
import java.util.Base64;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;

/**
 * @author Haoran Sun
 * @since 2024/08/27
 */

@Component
public class RSASignHelper {

    @Resource
    private ConstantsProperties constantsProperties;

    public String sign(String content) {
        Security.addProvider(new BouncyCastleProvider());
        try {
            Signature signature = Signature.getInstance("SHA256WithRSA","BC");
            signature.initSign(constantsProperties.getPrivateKey());
            signature.update(content.getBytes());
            return Base64.getEncoder().encodeToString(signature.sign());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public boolean verify(String content, String sign) {
        Security.addProvider(new BouncyCastleProvider());
        PublicKey publicKey = constantsProperties.getPublicKey();

        try {
            Signature signature = Signature.getInstance("SHA256WithRSA","BC");
            signature.initVerify(publicKey);
            signature.update(content.getBytes());
            return signature.verify(Base64.getDecoder().decode(sign));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
